package t327.Interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class StudentInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o)
            throws Exception {
        //创建session
        HttpSession session =request.getSession();

        //无需登录，允许访问的地址
        String[] allowUrls =new String[]{"login/userLogin"};

        //获取请求地址
        String url =request.getRequestURL().toString();



        for (String strUrl : allowUrls) {
            if(url.contains(strUrl)){
                return true;
            }
        }
        String id = request.getSession().getId();//获取sessionId
        ServletContext servletContext = request.getSession().getServletContext();
        String phone = (String)servletContext.getAttribute(id);//根据sessionId去作用域里查手机号

        if(phone==null){
            //重定向
            response.sendRedirect(request.getContextPath()+"/adminLogin.jsp");
            return false;
        }

        String id2 = (String)servletContext.getAttribute(phone);//如果能查到手机号
        if (id2==id){
            return true;
        }else {

            response.sendRedirect(request.getContextPath()+"/adminLogin.jsp");
        }

        //重定向
        //response.sendRedirect(request.getContextPath()+"/toLogin");


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView)
            throws Exception {
        System.out.println("CustomInterceptor....postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e)
            throws Exception {
        System.out.println("CustomInterceptor....afterCompletion");
    }
}